/*
========================================================================
 Name        : Test9Container2.cpp
 Author      : 
 Copyright   : Your copyright notice
 Description : 
========================================================================
*/
// [[[ begin generated region: do not modify [Generated System Includes]
#include <aknviewappui.h>
#include <eikappui.h>
#include <Test9.rsg>
// ]]] end generated region [Generated System Includes]

// [[[ begin generated region: do not modify [Generated User Includes]
#include "Test9Container2.h"
#include "Test9Container2View.h"
#include "Test9.hrh"
#include "Test9Container.hrh"
#include "Test9ListBox.hrh"
#include "Test9Container2.hrh"
// ]]] end generated region [Generated User Includes]
#include "Test9AppUi.h"
// [[[ begin generated region: do not modify [Generated Constants]
// ]]] end generated region [Generated Constants]

/**
 * First phase of Symbian two-phase construction. Should not 
 * contain any code that could leave.
 */
CTest9Container2::CTest9Container2()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	// ]]] end generated region [Generated Contents]
	
	view = ((CTest9AppUi*)iEikonEnv->AppUi())->iTest9Container2View;
	currentTrip.Load(iEikonEnv->FsSession(), view->strFilename);
	
	IsPaused = false;
	IsModified = false;
	IsUpkeyForward = true;
	}
/** 
 * Destroy child controls.
 */
CTest9Container2::~CTest9Container2()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	// ]]] end generated region [Generated Contents]
	
	}
				
/**
 * Construct the control (first phase).
 *  Creates an instance and initializes it.
 *  Instance is not left on cleanup stack.
 * @param aRect bounding rectangle
 * @param aParent owning parent, or NULL
 * @param aCommandObserver command observer
 * @return initialized instance of CTest9Container2
 */
CTest9Container2* CTest9Container2::NewL( 
		const TRect& aRect, 
		const CCoeControl* aParent, 
		MEikCommandObserver* aCommandObserver )
	{
	CTest9Container2* self = CTest9Container2::NewLC( 
			aRect, 
			aParent, 
			aCommandObserver );
	CleanupStack::Pop( self );
	return self;
	}

/**
 * Construct the control (first phase).
 *  Creates an instance and initializes it.
 *  Instance is left on cleanup stack.
 * @param aRect The rectangle for this window
 * @param aParent owning parent, or NULL
 * @param aCommandObserver command observer
 * @return new instance of CTest9Container2
 */
CTest9Container2* CTest9Container2::NewLC( 
		const TRect& aRect, 
		const CCoeControl* aParent, 
		MEikCommandObserver* aCommandObserver )
	{
	CTest9Container2* self = new ( ELeave ) CTest9Container2();
	CleanupStack::PushL( self );
	self->ConstructL( aRect, aParent, aCommandObserver );
	return self;
	}
			
/**
 * Construct the control (second phase).
 *  Creates a window to contain the controls and activates it.
 * @param aRect bounding rectangle
 * @param aCommandObserver command observer
 * @param aParent owning parent, or NULL
 */ 
void CTest9Container2::ConstructL( 
		const TRect& aRect, 
		const CCoeControl* aParent, 
		MEikCommandObserver* aCommandObserver )
	{
	if ( aParent == NULL )
	    {
		CreateWindowL();
	    }
	else
	    {
	    SetContainerWindowL( *aParent );
	    }
	iFocusControl = NULL;
	iCommandObserver = aCommandObserver;
	InitializeControlsL();
	SetRect( aRect );
	ActivateL();
	// [[[ begin generated region: do not modify [Post-ActivateL initializations]
	// ]]] end generated region [Post-ActivateL initializations]
	
	}
			
/**
* Return the number of controls in the container (override)
* @return count
*/
TInt CTest9Container2::CountComponentControls() const
	{
	return ( int ) ELastControl;
	}
				
/**
* Get the control with the given index (override)
* @param aIndex Control index [0...n) (limited by #CountComponentControls)
* @return Pointer to control
*/
CCoeControl* CTest9Container2::ComponentControl( TInt aIndex ) const
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	switch ( aIndex )
		{
		}
	// ]]] end generated region [Generated Contents]
	
	// handle any user controls here...
	
	return NULL;
	}
				
/**
 *	Handle resizing of the container. This implementation will lay out
 *  full-sized controls like list boxes for any screen size, and will layout
 *  labels, editors, etc. to the size they were given in the UI designer.
 *  This code will need to be modified to adjust arbitrary controls to
 *  any screen size.
 */				
void CTest9Container2::SizeChanged()
	{
	CCoeControl::SizeChanged();
	LayoutControls();
	// [[[ begin generated region: do not modify [Generated Contents]
			
	// ]]] end generated region [Generated Contents]
	
	}
				
// [[[ begin generated function: do not modify
/**
 * Layout components as specified in the UI Designer
 */
void CTest9Container2::LayoutControls()
	{
	}
// ]]] end generated function

/**
 *	Handle key events.
 */				
TKeyResponse CTest9Container2::OfferKeyEventL( 
		const TKeyEvent& aKeyEvent, 
		TEventCode aType )
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	
	if ( HandleTest9Container2OfferKeyEventL( aKeyEvent, aType ) == EKeyWasConsumed )
		{
		return EKeyWasConsumed;
		}
	
	// ]]] end generated region [Generated Contents]
	
	if ( iFocusControl != NULL
		&& iFocusControl->OfferKeyEventL( aKeyEvent, aType ) == EKeyWasConsumed )
		{
		return EKeyWasConsumed;
		}
	return CCoeControl::OfferKeyEventL( aKeyEvent, aType );
	}
				
// [[[ begin generated function: do not modify
/**
 *	Initialize each control upon creation.
 */				
void CTest9Container2::InitializeControlsL()
	{
	
	}
// ]]] end generated function

/** 
 * Handle global resource changes, such as scalable UI or skin events (override)
 */
void CTest9Container2::HandleResourceChange( TInt aType )
	{
	CCoeControl::HandleResourceChange( aType );
	SetRect( iAvkonViewAppUi->View( TUid::Uid( ETest9Container2ViewId ) )->ClientRect() );
	// [[[ begin generated region: do not modify [Generated Contents]
	// ]]] end generated region [Generated Contents]
	
	}
				
/**
 *	Draw container contents.
 */				
void CTest9Container2::Draw( const TRect& aRect ) const
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	CWindowGc& gc = SystemGc();
	gc.Clear( aRect );
	
	// ]]] end generated region [Generated Contents]
	
	}
bool CTest9Container2::AddLocation(const TDesC* aOverrideText, TDes* result)
	{
	TBuf<50> aData;
	if(view->RunDataQuery1L(aData, true, aOverrideText) != 0)
		{
		if(result != NULL)
			*result = aData;
		
		return true;
		}
	return false;
	}

TBuf<50> CTest9Container2::GetLocationName(bool IsDeleteLocation)
	{
	int arrLen = currentTrip.paths.Count();
	CDesCArrayFlat* locations = new (ELeave) CDesCArrayFlat(20);
	CleanupStack::PushL( locations );
	if(!IsDeleteLocation)
		locations->AppendL(currentTrip.paths[0]->start.name);
	
	for(TInt i=1 ; i<arrLen ; i++)
		locations->AppendL(currentTrip.paths[i]->start.name);
	
	if(!IsDeleteLocation)
		locations->AppendL(currentTrip.paths[arrLen-1]->end.name);
	
	TInt selected = view->RunListQuery1L(0, locations, 0);
	if(selected == -1)
		return _L("");
	
	TBuf<50> locName;
	locName.Append(locations->MdcaPoint(selected));
	return locName;
	}

/** 
 * Handle the offerKeyEvent event.
 */
TKeyResponse CTest9Container2::HandleTest9Container2OfferKeyEventL( 
		const TKeyEvent& aKeyEvent, 
		TEventCode aType )
	{
	// TODO: implement offerKeyEvent event handler
	
	if(aKeyEvent.iScanCode == 53)	//Do not go to LoadTripView.
		return EKeyWasConsumed;
	
	if(aKeyEvent.iScanCode == 50 && aType == EEventKeyUp)	// Num2 Pause \ Resume
		{
		IsPaused = !IsPaused;
		_LIT(pause, "Pause");
		_LIT(resume, "Resume");
		if(IsPaused)
			view->RunNote1L(&pause);
		else
			view->RunNote1L(&resume);
		}
	
	if(IsPaused)
		return EKeyWasNotConsumed;
	
	//if(aKeyEvent.iScanCode == 51 && aType == EEventKeyUp)	// Num3 Upkey moves forward\backward
		//{
		//UpKeyForwardBackwardSwitch();
		//return EKeyWasConsumed;
		//}
	
	//if (upArrow AND notPaused) then consumeStep
	//aType == EEventKeyUp 		The event is now working with the UpArrow
	//aKeyEvent.iRepeats == 0	Next
	if(aKeyEvent.iRepeats == 0 && aKeyEvent.iCode == EKeyUpArrow)	// Adding EventKeyUp condition (to fire only when the button releases)	
		{
		TBuf<50> action;
		if(IsUpkeyForward)
			action = currentTrip.MoveStepForward();
		else
			action = currentTrip.MoveStepBackward();
		
		if(action.Length() != 0)
			{
			view->RunNote1L(&action);
			}
		}
	
	if(aKeyEvent.iScanCode == 49 && aType == EEventKeyUp)	//Add Location	
		{
		_LIT(locationName, "Please enter location name");
		TBuf<50> aData;
		if(AddLocation(&locationName, &aData))
			{
				if(currentTrip.InsertNewLocation(aData))
					IsModified = true;
			}
		
		return EKeyWasConsumed;
		}
	
	if(aKeyEvent.iScanCode == 52 && aType == EEventKeyUp)	//Go to Location
		{
		TBuf<50> locName = GetLocationName();
		if(locName.Length() == 0)
			return EKeyWasConsumed;
		
		currentTrip.ResetWalk();
		TBuf<50> action = currentTrip.paths[0]->start.name;
		//Move till the step == the chosen location name
		while(true)
			{
			if(action == locName)
				break;
			if(action == _L("End"))
				break;
			
			if(IsUpkeyForward)
				action = currentTrip.MoveStepForward();
			else
				action = currentTrip.MoveStepBackward();
			}
		
		//_LIT(dbg, "acc");
		//delete[] locations;
		//view->RunConfQuery1L(&dbg);
		}
	
	if(aKeyEvent.iScanCode == 48 && aType == EEventKeyUp)	//View Trip Summery (Percentage only)
		{
		TBuf<20> percentage;
		percentage.Append(_L("You walked "));
		percentage.AppendNum(currentTrip.GetWalkedPercentage());
		percentage.Append(_L("%"));
		view->RunNote1L(&percentage);
		}
	
	if(aKeyEvent.iScanCode == 56 && aType == EEventKeyUp)	//View Trip Summery
		{
		//iEikonEnv->AlertWin(currentTrip.ViewTrip());
		//view->RunNote1L(&currentTrip.ViewTrip());
		view->RunConfQuery1L(&currentTrip.ViewTrip());
		}
	if(aKeyEvent.iScanCode == 55 && aType == EEventKeyUp)	//Reverse Trip
		{
		if(!currentTrip.IsWalking)
			{
			currentTrip.Reverse();
			_LIT(msg, "Trip reversed");
			view->RunNote1L(&msg);
			}
		}
	
	return EKeyWasNotConsumed;
	}

void CTest9Container2::UpKeyForwardBackwardSwitch()
	{
	IsUpkeyForward = !IsUpkeyForward;
	_LIT(forward, "Up key will move forward");
	_LIT(backward, "Up key will move backward");
	if(IsUpkeyForward)
		view->RunNote1L(&forward);
	else
		view->RunNote1L(&backward);
	}

bool CTest9Container2::DeleteLocation()
	{
	TBuf<50> locName = GetLocationName(true);
	if(locName.Length() == 0)
		return false;
	
	if(currentTrip.DeleteLocation(locName))
		{
		IsModified = true;
		return true;
		}
	return false;
	}

bool CTest9Container2::RenameLocation()
	{
	TBuf<50> locName = GetLocationName();
	if(locName.Length() == 0)
		return false;

	_LIT(locationName, "Please enter the new location name");
	TBuf<50> aData;
	if(AddLocation(&locationName, &aData))
		{
			if(currentTrip.RenameLocation(locName, aData))
				{
				IsModified = true;
				return true;
				}
		}
	
	return false;
	}

bool CTest9Container2::SaveChanges()
	{
	if(IsModified == true)
	{
		_LIT(question, "Do you want to save your changes?");
		if(view->RunConfQuery1L(&question) != 0)
			{
			currentTrip.Save(iEikonEnv->FsSession());
			IsModified = false;
			}
	}
	return true;
	}
